package com.zyf.springcloud.service.iml;

import com.zyf.springcloud.config.SelfUserDetails;
import com.zyf.springcloud.model.User;
import com.zyf.springcloud.result.Result;
import com.zyf.springcloud.service.OpenFeignEducationAPI;
import com.zyf.springcloud.service.OpenFeignEducationUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;
/*
认证部分
 */
@Component
public class SelfUserDetailsService implements UserDetailsService {
    @Autowired
    OpenFeignEducationUser openFeignEducationUser;
    @Autowired
    OpenFeignEducationAPI openFeignEducationAPI;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //构建用户信息的逻辑(取数据库/LDAP等用户信息)

        SelfUserDetails userInfo = new SelfUserDetails();
        User user = openFeignEducationUser.selectByName(username);
        if (user==null){
            return null;
        }
        userInfo.setUsername(username);
        //如果数据库里面的密码已经加密了就不用执行此步骤，记得加密方法要与websecurityconfig中一致
        userInfo.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
        String RoleName = openFeignEducationAPI.selectRoleNameByUserName(username);

        Set authoritiesSet = new HashSet();
        GrantedAuthority authority = new SimpleGrantedAuthority(RoleName);
        authoritiesSet.add(authority);
        userInfo.setAuthorities(authoritiesSet);

        return userInfo;
    }
}
